package net.wanho.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import net.wanho.po.Order;
import net.wanho.mapper.OrderMapper;
import net.wanho.service.OrderService;
import net.wanho.vo.MessageVo;
import net.wanho.websocket.WebSocketServer;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;


/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 汤小洋
 * @since 2025-09-25
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final RestTemplate restTemplate;
    private final WebSocketServer webSocketServer;

    /**
     * 订单表分页查询
     * @param pageNum
     * @param pageSize
     * @param order
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public PageInfo findPage(int pageNum, int pageSize, Order order) {
        if(ObjectUtil.isNull(order)){
            order = new Order();
        }

        // 分页
        PageHelper.startPage(pageNum,pageSize);
        List<Order> orderList = orderMapper.select(order);
        return new PageInfo(orderList);
    }

    /**
     * 根据主键查询订单表
     * @param orderId
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public Order findById(Serializable orderId) {
        return orderMapper.selectById(orderId);
    }

    /**
     * 订单表新增
     * @param order
     */
    @Override
    public void add(Order order) {
        orderMapper.insert(order);
    }

    /**
     * 修改订单表
     * @param order
     */
    @Override
    public void modify(Order order) {
        orderMapper.update(order);
    }

    /**
     * 根据主键删除订单表
     * @param orderId
     */
    @Override
    public void removeById(Serializable orderId) {
        if(((String)orderId).contains(",")){
            orderMapper.deleteByIds(((String)orderId).split(","));
        }else {
            orderMapper.deleteById(orderId);
        }
    }

    @Override
    public JSONObject findLogistics(String no) {
        String url = "https://wuliu.market.alicloudapi.com/kdi?no=" + no;
        String appcode = "bb9e19e7dae044919cfd6228a11f20cb";

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "APPCODE " + appcode);
        HttpEntity<String> entity = new HttpEntity<>(headers);

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        String body = response.getBody();

        JSONObject jsonObject = JSONObject.parseObject(body);
        if(!jsonObject.getString("status").equals("0")){
            throw new RuntimeException("物流信息查询失败：" + jsonObject.getString("msg"));
        }

        return jsonObject.getJSONObject("result");
    }

    @Override
    public void reminder(Integer orderId) {
        MessageVo messageVo = new MessageVo();
        messageVo.setType(1);
        messageVo.setOrderId(orderId);
        messageVo.setOrderNumber(orderMapper.selectById(orderId).getOrderNumber());

        webSocketServer.sendToAllClient(JSONUtil.toJsonStr(messageVo));
    }

    @Override
    public Order findByOrderNo(String outTradeNo) {
        return orderMapper.selectByOrderNo(outTradeNo);
    }

    @Override
    public void modifyStatus(Integer orderId, int status) {
        orderMapper.updateStatus(orderId, status);
    }
}
